
import * as Api from '../../utils/api.js'
var app = getApp()
Page({
  data: {
    info:{},
    userId: null,
    items: [
    ],
    selectCarts: [],
    allselect: false,
    allPrice: 0,
    cartsLen: 0,
    startX: 0, //开始坐标
    startY: 0,
    num: 1
  },

  goPdDatil(e) {
    wx.navigateTo({
      url: '../product_datil/product_datil?id=' + e.currentTarget.dataset.goodid,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // 取消商品选择
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  //去结算
  goShop: function (e) {
    let self = this

    if (this.data.selectCarts.length == 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请选择至少一个商品结算',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
      return
    }

    if (!this.hasGoneAway) {
      this.setData({ hasGoneAway: true })


      let url = app.globalData.baseUrl1 + '/order/checkprice';

      let data = {
        token: app.globalData.token,
        userId: app.globalData.userId,
        cartIdList: this.data.selectCarts.join(',')
      }
      let callBack = (res) => {
        console.log('判断购物车价格是否有改变', res.data)
        if (res == null) {

          console.log("网络请求错误！");
          return;
        }

        if (res.data.status != 200) {
          wx.showModal({
            title: res.data.message,
            content: '',
            showCancel: false,
            cancelColor: '',
            confirmColor: '',
            success: function (res) {
              self.setData({ hasGoneAway: false })
            },
            fail: function (res) { },
            complete: function (res) { },
          })
          return;
        }
        if (res.data.status === 200) {
          wx.navigateTo({
            url: '../../example/order_list/order_list?pagetype=carts&id=' + this.data.selectCarts.join(',')
          })
        }

      }
      Api.reqFormPost(url, data, callBack)







    }
  },
  //全选
  selectall() {
    let info = this.data.info
    let count = false
    let selectCarts = []

    for (let i = 0; i < info.length; i++) {

      if (this.data.allselect) {
        info[i].select = false
      } else {
        info[i].select = true,

          selectCarts.push(info[i].cartId)
      }

    }

    this.setData({
      allselect: !this.data.allselect,
      info: info,
      selectCarts: selectCarts
    })
    this.handleCartMoney()

  },
  //购物车合计金额
  handleCartMoney() {
    // item.price * item.num
    console.log(this.data.info)
    let allPrice = 0
    for (let i = 0; i < this.data.info.length; i++) {
      if (this.data.info[i].select) {
        allPrice = (allPrice + (this.data.info[i].price * this.data.info[i].num))
      }
    }
    this.setData({
      allPrice: allPrice.toFixed(2)
    })
  },



  addnum(e) {

    let info = this.data.info
    console.log('++++++')
    if (e.currentTarget.dataset.type == 'add') {
      console.log('++++++')
      console.log(info[e.currentTarget.dataset.index])
      info[e.currentTarget.dataset.index].num = info[e.currentTarget.dataset.index].num + 1
    } else {
      if (info[e.currentTarget.dataset.index].num === 1) {
        return
      }
      info[e.currentTarget.dataset.index].num = info[e.currentTarget.dataset.index].num - 1
    }
    this.setData({
      info: info
    })
    let self = this

    let url = app.globalData.baseUrl1 + '/shopcart/update';

    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      cartId: info[e.currentTarget.dataset.index].cartId,
      num: info[e.currentTarget.dataset.index].num
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误！");
        return;
      }

      if (res.data.status != 200) {
        console.log("请求数据错误" + url);
        return;
      }
      if (res.data.status === 200) {
        self.handleCartMoney()

      }

    }
    Api.reqFormPost(url, data, callBack)
  },

  /**    * 生命周期函数--监听页面显示    */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    }

    if (app.globalData.merchant.mustLogin || app.globalData.userId === null) {
      if (app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }
    }
    this.setData({ hasGoneAway: false })
    this.getCarList();
    this.setData({
      allselect: false,
      selectCarts: [],
      allPrice: 0
    })
    
  },

  //选择商品
  selectproduct(e) {
    console.log('111')
    let info = this.data.info
    let selectCarts = this.data.selectCarts
    let allselect = true


    info[e.currentTarget.dataset.index].select = !info[e.currentTarget.dataset.index].select
    if (info[e.currentTarget.dataset.index].select) {

      selectCarts.push(info[e.currentTarget.dataset.index].cartId)
    } else {

      this.removeByValue(selectCarts, info[e.currentTarget.dataset.index].cartId)
    }
    if (selectCarts.length === info.length) {
      allselect = true
    } else {
      allselect = false
    }
    this.setData({
      selectCarts: selectCarts,
      info: info,
      allselect: allselect
    })
    this.handleCartMoney()
  },
  //取购物车列表
  getCarList: function () {
    let self = this
    let url = app.globalData.baseUrl1 + '/shopcart/query';

    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      console.log(res)
      console.log('-------------')
      if (res.data.status === 200) {
        let items = []

        if (res.data.data[0]) {

          for (let i = 0; i < res.data.data[0].cartlist.length; i++) {
            res.data.data[0].cartlist[i].select = false
            items[i] = { isTouchMove: false }
          }
        } else {
          res.data.data[0] = { cartlist: [] }
        }


        self.setData({
          info: res.data.data[0].cartlist,
          cartsLen: res.data.data[0].cartlist.length,
          items: items
        })


      }

    }
    Api.reqFormPost(url, data, callBack)

  },
  onLoad: function () {
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow);
      return
    }
    this.setData({
      userId: app.globalData.userId
    })
    
  },
  
  // ifcomit(e){
  //   let self =this
  //   let opt = e.currentTarget.dataset.funtype

  //   let count = 0
  //   this.data.items.forEach(function (v, i) {
  //     if (v.isTouchMove)//只操作为true的
  //     {
  //       count++
  //     }
  //     console.log(opt == 'goPdDatil',count)
  //   })
 

  //   if (opt !== 'goPdDatil' && count > 0) {
  //     self.cancelDel()

  //   // setTimeout(()=>{
  //   //   console.log('关闭')
  //   // },500)
  
  //   return
  // } else if (opt == 'goPdDatil' && count === 0) {
  //   console.log('count==0')

  //   this.goPdDatil(e)
  // } else if (opt !== 'goPdDatil' && count === 0){
  //     console.log('开启滑动')

  //   this.touchstart(e)
  //   return
  // }
  
  // },
  cancelDel(e){
    //开始触摸时 重置所有删除
    this.data.items.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      items: this.data.items,
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {

    this.cancelDel()
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,

    })

  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.items.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
         {
          v.isTouchMove = false
         }
        else //左滑
       {
          v.isTouchMove = true
       }
      }
    })
    //更新数据
    that.setData({
      items: that.data.items,
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  goLogin: function () {
    wx.navigateTo({
      url: '../login/login',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //删除事件
  del: function (e) {

    let self = this
    let url = app.globalData.baseUrl1 + '/shopcart/delete';

    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      cartId: this.data.info[e.currentTarget.dataset.index].cartId
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      console.log(res)
      console.log('-------------')
      if (res.data.status === 200) {

        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        })


        // self.getCarList();
        self.removeByValue(self.data.info, self.data.info[e.currentTarget.dataset.index])
        self.handleCartMoney()
        self.setData({
          info: self.data.info
        })
      }

    }
    Api.reqFormPost(url, data, callBack)

  }
})